import { defineStore } from 'pinia';
import { getBusinessList, getBusinessById, getPoolList } from '@/api/business';

export const useBusinessStore = defineStore('business', {
  state: () => ({
    // 商机列表
    businesses: [],
    // 公海池列表
    poolList: [],
    // 当前商机详情
    currentBusiness: null,
    // 分页信息
    pagination: {
      page: 1,
      pageSize: 10,
      total: 0
    },
    // 加载状态
    loading: false,
    // 初始化状态
    initialized: false
  }),

  getters: {
    // 获取分页后的商机列表
    paginatedBusinesses: (state) => {
      return state.businesses;
    },

    // 获取分页后的公海池列表
    paginatedPoolList: (state) => {
      return state.poolList;
    }
  },

  actions: {
    // 初始化商机数据
    async initializeBusinesses() {
      if (this.initialized) return;
      this.loading = true;
      try {
        await this.fetchBusinesses();
        this.initialized = true;
      } catch (error) {
      } finally {
        this.loading = false;
      }
    },

    // 获取商机列表
    async fetchBusinesses(params = {}) {
      this.loading = true;
      try {
        const response = await getBusinessList({
          page: this.pagination.page,
          pageSize: this.pagination.pageSize,
          ...params
        });
        if (response.code === 1) {
          this.businesses = response.data.rows || [];
          this.pagination.total = response.data.total || 0;
        }
        return response;
      } catch (error) {
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 获取商机详情
    async fetchBusinessDetail(id) {
      try {
        const response = await getBusinessById(id);
        if (response.code === 1) {
          this.currentBusiness = response.data;
        }
        return response;
      } catch (error) {
        throw error;
      }
    },

    // 获取公海池列表
    async fetchPoolList(params = {}) {
      this.loading = true;
      try {
        const response = await getPoolList({
          page: this.pagination.page,
          pageSize: this.pagination.pageSize,
          ...params
        });
        if (response.code === 1) {
          this.poolList = response.data.rows || [];
          this.pagination.total = response.data.total || 0;
        }
        return response;
      } catch (error) {
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 设置分页信息
    setPagination(page, pageSize) {
      this.pagination.page = page;
      this.pagination.pageSize = pageSize;
    },

    // 刷新商机数据
    async refreshBusinesses() {
      await this.fetchBusinesses();
    },

    // 清空当前商机
    clearCurrentBusiness() {
      this.currentBusiness = null;
    },

    // 重置状态
    resetState() {
      this.businesses = [];
      this.poolList = [];
      this.currentBusiness = null;
      this.pagination = {
        page: 1,
        pageSize: 10,
        total: 0
      };
      this.initialized = false;
    }
  }
});